<?php
/**
 * 根据URL获取顶级域名
 * @author 蓝优 <1410469560@qq.com>
 * @link   https://lanyou.vip
 */
declare(strict_types=1);

class AuthzVerify
{
    public static function Accept($domain)
    {
        $row = self::DomainAssay($domain);
        return self::GetHost($row);
    }
    /**
     * @param $domain 域名分析
     */
    private static function DomainAssay($domain)
    {
        preg_match("/^http(s)?:\/\/(.*?)\//", $domain, $match);
        $result = !empty($match[2]) ? $match[2] : $domain;
        return $result;
    }
    
    /**
     * 域名后缀
     */
    private static function TQSuffix()
    {
        return array("top","cn","com","net","xyz","icu","shop","club","cc","vip","ltd","site","ink","art","co","cloud","ren","asia","work","fit","biz","pub","love","online","info","wang","fans","store","red","mobi","kim","com.cn","net.cn","gov.cn","link","tech","pro","xin","me","fun","website","band","cab","cafe","fan","games","market","mba","shopping","studio","tax","technology","law","green","school","global","monster","college","space","group","design","wiki","gold","life","fund","city","world","cool","company","zone","today","chat","show","email","plus","center","team","live","video","guru","bond","social","run","beer","yoga","fashion","luxe","host","press","blue","pet","pink","black","organic","bio","baby","rent","cash","fyi","vin","media","news","sale","cyou","tv","org.cn","ac.cn","bj.cn","sh.cn","tj.cn","cq.cn","he.cn","sn.cn","sx.cn","nm.cn","ln.cn","jl.cn","hl.cn","js.cn","zj.cn","ah.cn","fj.cn","jx.cn","sd.cn","ha.cn","hb.cn","hn.cn","gd.cn","gx.cn","hi.cn","sc.cn","gz.cn","yn.cn","gs.cn","qh.cn","nx.cn","xj.cn","tw.cn","hk.cn","mo.cn","xz.cn","ski","lotto","poker","promo","vote","archi","voto");
    }
    /**
     * 获取顶级域名
     */
    private static function GetHost($verifyurl= '')
    {
        $url = $verifyurl ? $verifyurl : $_SERVER['HTTP_HOST'];
        $domainArr = array_reverse(explode('.', $url));
        $count = count($domainArr);
        $Suffix = self::TQSuffix();
        $single = $domainArr[0];
        $twin = $domainArr[1].'.'.$domainArr[0];
        if (in_array($twin, $Suffix) && $count != 2) {
            return $domainArr[2].'.'.$twin;
        } elseif (in_array($single, $Suffix) && $count != 4) {
            return $twin;
        } else {
            return $url;
        }
    }
}
